//
//  LoginViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/9/16.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "LoginViewController.h"
#import "TBConfigure.h"
#import "LoginChooseModel.h"
#import "LoginTableViewCell.h"
#import "CustomBtnTableViewCell.h"
#import "LoginHeadView.h"
#import "BaseReqApi.h"
#import "LoginStatuesModel.h"
#import "UserLoginName.h"
#import "HomeViewController.h"
#import "AppDelegate+AppService.h"
#import "GotoCheckViewController.h"//商户注册
@interface LoginViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)TB_TableView *mainTableview;

@property(nonatomic,strong)LoginHeadView *headview;

@property(nonatomic,strong)NSMutableArray *dataArr;

@property(nonatomic,assign)BOOL isChooseJob;//是否进入选择角色模式

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:kColorRGBA(0x2E4361, 1)] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
 
    self.isHidenKeyToolBar=YES;
    
    self.isChooseJob=NO;
    
    self.view.backgroundColor=TBColorAppTheme;
    
    [self.view addSubview:self.mainTableview];
    // Do any additional setup after loading the view.
}

#pragma mark-懒加载
-(NSMutableArray*)dataArr
{
    if (!_dataArr) {
        _dataArr=[NSMutableArray array];
        
        NSDictionary *UserPWd=[UserLoginName GetLoginInfor];
  
        for (NSInteger i=0; i<3; i++) {
            
            LoginChooseModel *choose=[LoginChooseModel new];
            
            choose.index=i;
            
            switch (i) {
                case 0:
                {
                    
                    choose.imageMark=@"userType";
                    
                    choose.ploacherText=@"请选择身份";
                    
                    choose.enable=NO;
                    
                    choose.isSecrue=NO;
                    
                    choose.showArror=YES;
                    
                    choose.keyWord=@"loginType";
                    
                    choose.Type=1;
                    
                    choose.userWrite=@"商户";
                }
                    break;
                 case 1:
                {
                    
                    choose.imageMark=@"userName";
                    
                    choose.ploacherText=@"用户名";
                    
                    choose.enable=YES;
                    
                    choose.isSecrue=NO;
                    
                    choose.showArror=NO;
                    
                     choose.keyWord=@"loginName";
                }
                    break;
                case 2:
                {
                    
                    choose.imageMark=@"userPwd";
                    
                    choose.ploacherText=@"密码";
                    
                    choose.enable=YES;
                    
                    choose.isSecrue=YES;
                    
                    choose.showArror=YES;
                    
                     choose.keyWord=@"loginPwd";
                }
                    break;
                    
                default:
                    break;
            }
            if (UserPWd.count!=0) {
                //如果存在密码
                if (i==0) {
                    choose.Type=[UserPWd[@"loginType"]integerValue];

                    if (choose.Type==1) {
                        
                        choose.userWrite=@"商户";
                        
                    }else if (choose.Type==2)
                    {
                        choose.userWrite=@"检查员";
                    }else if (choose.Type==3)
                    {
                        choose.userWrite=@"开办方";
                    }else{
                        
                        choose.userWrite=@"管理员";
                    }

                }else if (i==1)
                {
                    choose.userWrite=UserPWd[@"loginName"];
                    
                }else{
                    
                     choose.userWrite=UserPWd[@"loginPwd"];
                }
     
            }
    
            [_dataArr addObject:choose];
        }
        
    }
    
    return _dataArr;
}



-(TB_TableView*)mainTableview
{
    if (!_mainTableview) {
        _mainTableview=[[TB_TableView alloc]initWithFrame:CGRectMake(30, 0, SCREEN_WIDTH-60, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
        _mainTableview.delegate=self;
        _mainTableview.dataSource=self;
        _mainTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_mainTableview registerNib:[UINib nibWithNibName:@"LoginTableViewCell" bundle:nil] forCellReuseIdentifier:@"uiqcell"];
        [_mainTableview registerNib:[UINib nibWithNibName:@"CustomBtnTableViewCell" bundle:nil] forCellReuseIdentifier:@"Btncell"];
        _mainTableview.tableFooterView=[[UIView alloc]init];
        _mainTableview.scrollEnabled=NO;
        _mainTableview.backgroundColor=TBColorAppTheme;
        
        _mainTableview.tableHeaderView=self.headview;
        
    }
    return _mainTableview;
}


-(LoginHeadView*)headview
{
    if (!_headview) {
     
        _headview=[[LoginHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-60, SCREEN_HEIGHT*0.35)];
        
    }
    return _headview;
}

#pragma mark-tableView代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.isChooseJob) {
     
        LoginChooseModel *model=self.dataArr[0];
        
        return model.jobArr.count+1;
    }
    
    return self.dataArr.count+1;
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isChooseJob) {
        
        LoginTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"uiqcell" forIndexPath:indexPath];
        
        if (indexPath.row==0) {
            
            LoginChooseModel *model=self.dataArr[indexPath.row];
       
            cell.model=model;
            
            cell.isChoose=self.isChooseJob;
            
            return cell;
            
        }else{
            
             LoginChooseModel *model=self.dataArr[0];
            
            JobModel *jmodel=model.jobArr[indexPath.row-1];
            
            cell.jmodel=jmodel;
            
            return cell;
        }
    }else{
   
    if (indexPath.row<self.dataArr.count) {
        
         LoginChooseModel *model=self.dataArr[indexPath.row];
        
        LoginTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"uiqcell" forIndexPath:indexPath];

        cell.LoginTextFile.bk_shouldReturnBlock = ^BOOL(UITextField *text) {
            
            [self.view endEditing:YES];
            
            return YES;
        };
        
        cell.LoginTextFile.bk_didBeginEditingBlock = ^(UITextField *text) {
          
            [UIView animateWithDuration:0.35 animations:^{
      
                [self.headview UpMoveAnation];
                
                self.headview.frame=CGRectMake(0, 0, SCREEN_WIDTH-60, SCREEN_HEIGHT*0.35-60);
                
                self.mainTableview.tableHeaderView=self.headview;
                
            }];
      
        };
        
        cell.LoginTextFile.bk_shouldEndEditingBlock = ^BOOL(UITextField *text) {
        
            [UIView animateWithDuration:0.35 animations:^{
                
                self.headview.frame=CGRectMake(0, 0, SCREEN_WIDTH-60, SCREEN_HEIGHT*0.35);
                
                self.mainTableview.tableHeaderView=self.headview;
                
                [self.headview DownMoveAnation];
                
            }];
            
            return YES;
        };
        
        [cell.LoginTextFile addTarget:self action:@selector(TextChange:) forControlEvents:UIControlEventEditingChanged];
        
        cell.LoginTextFile.tag=indexPath.row+2000;
        
        cell.model=model;
        
        cell.isChoose=self.isChooseJob;
      
        if (indexPath.row==2) {
            
            UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ChangeSecrect:)];
            
            cell.ArrorImageView.userInteractionEnabled=YES;
            
            [cell.ArrorImageView addGestureRecognizer:tap];
            
        }else{
            
            cell.ArrorImageView.userInteractionEnabled=NO;
            
        }
      
        
        return cell;
    }else{
        
        LoginChooseModel *model=self.dataArr[0];
        
        CustomBtnTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Btncell" forIndexPath:indexPath];
  
        if (model.Type==1||model.Type==3) {
            
            cell.RegisterBtn.hidden=NO;
        }else{
            
            cell.RegisterBtn.hidden=YES;
            
        }
        
        cell.block=^(NSInteger btnType)
        {
            
            if (btnType==1) {
                
             [self StartLogin];
                
            }else{
                
                if (model.Type==1) {
                    
                    GotoCheckViewController *GotoRegister=[GotoCheckViewController new];
                    
                    GotoRegister.userType=0;//用于商户注册
                    
                    GotoRegister.RegisterPeople=0;//自己注册
                    
                    [self.navigationController pushViewController:GotoRegister animated:YES];
                    
                    
                }else{
                
                    GotoCheckViewController *GotoRegister=[GotoCheckViewController new];
                    
                    GotoRegister.userType=2;//用于开办方注册
                    
                    [self.navigationController pushViewController:GotoRegister animated:YES];
        
                }
                    
            }
       
        };
        
        return cell;
    }
}

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (!self.isChooseJob) {
        
        if (indexPath.row<self.dataArr.count) {
            
            return 44*SCREEN_WIDTH/320.0;
        }
        
        return 100*SCREEN_WIDTH/320.0;
    }
    
    return 44;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        
        [self.view endEditing:YES];
        
        self.isChooseJob=!self.isChooseJob;
        
        [self.mainTableview reloadData];
        
    }else{
   
        if (self.isChooseJob) {
            
            LoginChooseModel *model=self.dataArr[0];
            
            JobModel *jmodel=model.jobArr[indexPath.row-1];
            
            model.userWrite=jmodel.JobName;
            
            model.Type=jmodel.jobType;
            
            self.isChooseJob=!self.isChooseJob;
            
            [self.mainTableview reloadData];
        }
    }
}

-(void)TextChange:(UITextField*)text{
    
    NSInteger tags=text.tag-2000;
    
    LoginChooseModel *model=self.dataArr[tags];

    model.userWrite=text.text;

}

-(void)StartLogin
{

    NSMutableDictionary*reqDict=[NSMutableDictionary dictionary];
    
    for (NSInteger i=0; i<self.dataArr.count; i++) {
        
        LoginChooseModel *model=self.dataArr[i];
   
            if (i==0) {
                
               [reqDict setValue:[NSString stringWithFormat:@"%ld",model.Type] forKey:model.keyWord];
            }else{
                
                [reqDict setValue:model.userWrite forKey:model.keyWord];
          
            }
    }

     [self showLoadingAnimation];
    
    BaseReqApi *LoginApi=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/login.json" andrequestTime:5 andParams:reqDict andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    [LoginApi StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
        
        LoginStatuesModel *model=[LoginStatuesModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            
            UserLoginName *umodel=[UserLoginName mj_objectWithKeyValues:reqDict];
            
            [UserLoginName SaveLoginInfor:umodel];
        
            [LoginStatuesModel SaveUserInforWithModel:model];
            
            AppDelegate * app = (AppDelegate*)[UIApplication sharedApplication].delegate;
            
            [app initUserManager];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
    
        }else{
            
            NSLog(@"404");
        }
        
    }];

}



-(void)ChangeSecrect:(UITapGestureRecognizer*)tap
{
    
    LoginChooseModel *model=self.dataArr[2];
    
    model.isSecrue=!model.isSecrue;
    
    [self.mainTableview reloadData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
